package com.eascs.paymentdetail.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.backfee.form.ComBackFeeForm;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.file.FileService;
import com.eascs.file.FileTypeConstants;
import com.eascs.pay.entity.O2oPayVo;
import com.eascs.paymentdetail.entity.O2oTransferAccount;
import com.eascs.paymentdetail.service.O2oTransferAccountService;
import com.eascs.paymentdetail.vo.O2oTransferAccountVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.type.SystemModule;
import com.eascs.workflow.form.ZXPTCWForm;

/**
 * @ClassName: O2oTransferAccountsRestController
 * @Description: 付款转账
 * @author 张庆奇
 * @date 2017年5月17日 上午10:50:57
 * @version V1.0
 */
@RestController
@RequestMapping("/transferAccountsRest")
public class O2oTransferAccountsRestController extends BaseRestController {
	private static Logger log = LoggerFactory.getLogger(O2oTransferAccountsRestController.class);

	@Autowired
	O2oTransferAccountService o2oTransferAccountService;
	@Reference
	private SequenceService sequenceService;
	@Autowired
	private BaseUtils baseUtils;
	
	@Reference
	private SysOrgService sysOrgService;
	
	@Autowired
	private FileService fileService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	/**
	 * @Title: add
	 * @Description: 弹出付款转账页面
	 * @author 张庆奇
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年5月17日 上午10:51:00
	 */
	@RequestMapping("/add")
	public BaseRestResult<String> add() {

		return HtmlRestResult.popHtmlFragment("paymentdetail/addTransferAccounts");
	}

	/**
	 * @Title: save
	 * @Description: 创建付款转账
	 * @author 张庆奇
	 * @param vo
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年5月18日 下午3:29:53
	 */
	@RequestMapping("/save")
	public BaseRestResult<String> save(O2oTransferAccountVo vo) {
		O2oTransferAccount entity = new O2oTransferAccount();
		if (StringUtils.isNotEmpty(vo.getId())) {
			entity = o2oTransferAccountService.findById(vo.getId());
			if (!"NEW".equals(entity.getBillStatus()) && !"BH".equals(entity.getBillStatus())) {
				return BaseRestResult.warn("已经有一个付款转账流程在流程中，请勿重复启动");
			}
		}
		
		ActOrgEntity actOrgEntity = null;
		
		if(vo.getLtd()==null){
			return BaseRestResult.warn("请选择经办平台");
		}
		
		actOrgEntity = sysOrgService.getOrgByUnitNo(vo.getLtd());
		if(actOrgEntity!=null){
			vo.setLtdCode(actOrgEntity.getUnitCode());
			vo.setLtdName(actOrgEntity.getOrgName());
		}else{
			return BaseRestResult.warn("所选经办平台在系统中未查询到，请核实后在输入。");
		}
		
		if (StringUtils.isEmpty(vo.getPayCompany())) {
			return BaseRestResult.warn("付款公司不能为空");
		}

		if (StringUtils.isEmpty(vo.getCollectionUserName())) {
			return BaseRestResult.warn("收款户名不能为空");
		}

		if (StringUtils.isEmpty(vo.getCollectionAccount())) {
			return BaseRestResult.warn("收款账号不能为空");
		}
		if (StringUtils.isEmpty(vo.getCollectionBankName())) {
			return BaseRestResult.warn("收款开户行不能为空");
		}
		if (vo.getPayAmount() == null) {
			return BaseRestResult.warn("付款金额不能为空");
		}

		if (StringUtils.isEmpty(vo.getCollectionBankAddress())) {
			return BaseRestResult.warn("汇入行地址不能为空");
		}
		
		entity.setPayCompany(vo.getPayCompany());
		entity.setCollectionUserName(vo.getCollectionUserName());
		entity.setCollectionAccount(vo.getCollectionAccount());
		entity.setCollectionBankName(vo.getCollectionBankName());
		entity.setPayAmount(vo.getPayAmount());
		entity.setCollectionBankAddress(vo.getCollectionBankAddress());
		entity.setPayRemark(vo.getPayRemark());
		entity.setLtd(vo.getLtd());
		entity.setLtdCode(vo.getLtdCode());
		entity.setLtdName(vo.getLtdName());
		int i = 0;
		if (StringUtils.isEmpty(vo.getId())) {
			entity.setBillCode(buildCode("FKZZ"));
			i = o2oTransferAccountService.save(entity);
			
			if (i > 0) {
				return BaseRestResult.buildCloseActionDialogResult()
						.andActionAjaxLoad("/transferAccountsRest/update?id=" + entity.getId());
				} else {
					return BaseRestResult.info("保存失败");
			}
			
		} else {
			i = o2oTransferAccountService.updateEntityById(entity);
		}

			/*//上传附件开始
			log.info("上传其他附件开始");
			fileService.upload(file, datalist, loanapplyno);
			log.info("上传其他附件结束");
			return BaseRestResult.buildClosestReloadResult();
			queryDataList(vo.getId(), FileTypeConstants.DALIST_TYPE_FKZZWJ,null);
			*/
		
		if (ComBackFeeForm.TYPE_SAVEANDSTART.equals(vo.getType())) { // 如果是保存并启动，调用启动方法
			// 先查出要启动的对象
			startPay(entity.getId());
		}

		if (i > 0) {
			return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/transferAccounts/index"));
			
		} else {
			return BaseRestResult.info("保存失败");
		}

	}

	/**
	 * @Title: startPay
	 * @Description: 发起付款转账流程
	 * @author 张庆奇
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年5月18日 下午3:29:11
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/startPay")
	public BaseRestResult<String> startPay(String id) {
		O2oTransferAccount o2oTransferAccount = o2oTransferAccountService.findById(id);
		if (o2oTransferAccount == null) {
			return BaseRestResult.warn("数据异常，请联系运维人员");
		}
		// 加一个是否有付款转账流程在运行中的判断

		boolean ishaspay = o2oTransferAccountService.isHaveRUNTransferAccountFlow(id);
		if (ishaspay) {
			return BaseRestResult.warn("已经有一个付款转账流程在流程中，请勿重复启动");
		}
		User user = UserHolder.getUser();

		try {
			com.eascs.workflow.common.vo.ModelResult<Boolean> model = o2oTransferAccountService
					.startPayFlow(o2oTransferAccount);
			if (model.isSuccess()) {
				log.info("财务管理付款转账流程数据成功，单据号为：{}", o2oTransferAccount.getBillCode());
				if (null != o2oTransferAccount) {

					o2oTransferAccount.setBillStatus(StatusContexts.O2O_BANK_RUN);
					o2oTransferAccountService.updateEntityById(o2oTransferAccount);
					log.info("财务管理付款转账流程数据成功，单据号为：{},更新付款转账数据成功", o2oTransferAccount.getBillCode());
					return BaseRestResult.info("财务管理付款转账流程启动成功").andRefresh();
				}
			} else {
				log.error("财务管理付款转账流程数据失败，单据号为：{},失败原因：{}", o2oTransferAccount.getBillCode(), model.getErrMsg());
				return BaseRestResult.warn("财务管理付款转账流程启动失败，请联系管理员。失败原因：" + model.getErrMsg());
			}
		} catch (Exception e) {
			log.error("error财务管理付款转账插入启动付款流程数据失败,单据号为：{},失败原因：{}", o2oTransferAccount.getBillCode(), e.getMessage());
			return BaseRestResult.warn("财务管理付款转账流程启动失败，请联系管理员。失败原因：" + e.getMessage());
		}
		return BaseRestResult.warn("财务管理付款转账流程启动异常");
	}

	/**
	 * @Title: payApprola
	 * @Description:代办管理页面
	 * @author 张庆奇
	 * @param vo
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年5月18日 下午3:50:52
	 */
	@RequestMapping("/pay_approval")
	public BaseRestResult<String> payApprola(O2oPayVo vo) {
		O2oTransferAccount o2oTransferAccount = o2oTransferAccountService.findById(vo.getReferId());
		//获取登录人信息
		User user = UserHolder.getUser();
		if (o2oTransferAccount == null) {
			return BaseRestResult.warn("未查询到付款转账单据号，请联系管理员");
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(vo.getReferId(), null, SystemModule.SYSTEM_MODULE_O2O);
		String approvalUrl = baseUtils.getApprovalUrl(vo.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", o2oTransferAccount);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("approvalStatus", vo.getApprovalStatus());
		
		queryDataList(o2oTransferAccount.getId(), FileTypeConstants.DALIST_TYPE_FKZZWJ,null);
		ViewContext.put("user", user);
		return HtmlRestResult.popHtmlFragment("paymentdetail/pay_approval");
	}

	/**
	 * 生成付款转账编号
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	public String buildCode(String code) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, StatusContexts.O2O_SEQUENCE_LENGTH, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}
	
	/**
	 * @Title: print
	 * @Description:
	 * @author 张庆奇
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年5月19日 下午2:03:18
	 */
	@RequestMapping("/print")
	public BaseRestResult<String> print(String id) {
		O2oTransferAccount o2oTransferAccount = o2oTransferAccountService.findById(id);
		if (o2oTransferAccount == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(id, null, SystemModule.SYSTEM_MODULE_O2O);
		Date date = new Date();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		ViewContext.put("printDate", s.format(date));
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", o2oTransferAccount);
		return HtmlRestResult.popHtmlFragment("paymentdetail/print");
	}
	
	@RequestMapping("/delete")
	public BaseRestResult<String> delete(String  id){
		O2oTransferAccount entity = o2oTransferAccountService.findById(id);
		entity.setIsDel("Y");
		int  i= o2oTransferAccountService.updateEntityById(entity);
		if (i > 0) {
			 return BaseRestResult.info("删除成功").andRefresh();
		} else {
			return BaseRestResult.info("删除失败");
		}
	}
	
	@RequestMapping("/update")
	public HtmlRestResult update(String  id){
		O2oTransferAccount entity = o2oTransferAccountService.findById(id);
		ViewContext.put("vo", entity);
		return HtmlRestResult.popHtmlFragment("paymentdetail/addTransferAccounts");
		
	}
	
	/**
	 * 
	 * 上传付款转账文件
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/upload_view")
	public HtmlRestResult output(String id) {
		
		queryDataList(id, FileTypeConstants.DALIST_TYPE_FKZZWJ,null);
		ViewContext.put("loanapplyNo", id);
		return HtmlRestResult.html("paymentdetail/upload_view");
	}

	
	public void queryDataList(String loanapplyNo, String code,String type) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		AjaxConfirmButton[] dealButton=null;
		/*if(type==null){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		} else if(type.equals("NS_XDJL")){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		}*/
		paginationInfo.setMoreButtons(dealButton);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	
}
